﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Core.Helper
{
    public static class RegisterHelper
    {
        public static bool IsRegisted { get; set; } = false;
        public static DateTime TryDateTime { get; } = DateTime.Now;
        public static int TryHours { get; } = 3;
        public static bool IsExpire = false;
        public static string RegSerial
        {
            get;
            private set;
        }
        public static string ExpireRegCode
        {
            get;
            private set;
        }
        public static string ExtensionStr { get; } = "Visual2020";
        private static string softWareName = "DataServer";

        public static DateTime RegistTime { get; private set; } = DateTime.Now;
        public static DateTime ExpireTime { get; private set; } = DateTime.Now.AddDays(-1);

        public static bool CheckRegisteState()
        {
            string msgString = "";
            string strSerial = (Computer.CurrentIns.AuthSerialID + ExtensionStr).GetHashCode().ToString();
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] palindata = Encoding.Default.GetBytes(strSerial);//将要加密的字符串转换为字节数组
            byte[] encryptdata = md5.ComputeHash(palindata);//将字符串加密后也转换为字符数组
            msgString = Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为加密字符串
            try
            {
                Microsoft.Win32.RegistryKey retkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software", true).OpenSubKey("PowerVisual").OpenSubKey("checkid");
                string keyValue = (string)retkey.GetValue(softWareName);

                Microsoft.Win32.RegistryKey registTime = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software", true).OpenSubKey("PowerVisual").OpenSubKey("begintime");
                string strDate = (string)registTime.GetValue("begintime");

                Microsoft.Win32.RegistryKey overTime = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software", true).OpenSubKey("PowerVisual").OpenSubKey("expire");
                string strExpire = (string)overTime.GetValue("expire");
                ExpireRegCode = strExpire;
                if (msgString == keyValue)
                {

                    var date = EncryptHelper.DecryptDES(strDate, "01250222");
                    DateTime resTime;
                    if (DateTime.TryParse(date, out resTime))
                    {
                        RegistTime = resTime;
                        IsRegisted = true;
                        RegSerial = msgString;
                        date = EncryptHelper.DecryptDES(strExpire, "02220125");
                        if (DateTime.TryParse(date, out resTime))
                        {
                            ExpireTime = resTime;
                        }
                    }
                    else
                    {
                        IsRegisted = false;
                        RegSerial = msgString;
                    }
                    return IsRegisted;
                }
            }
            catch
            {
                IsRegisted = false;
                return false;
            }
            IsRegisted = false;
            return false;
        }

        public static bool CheckIsExpire()
        {
            if (DateTime.Compare(ExpireTime, DateTime.Now) > 0 && DateTime.Compare(RegistTime, DateTime.Now) < 0)
            {
                IsExpire = false;
                return false;
            }
            IsExpire = true;
            return true;
        }

        public static bool RegisteSolfware(string strSerial)
        {
            string strExpire =
                EncryptHelper.EncryptDES(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss"), "02220125");
            return RegisteSolfware(strSerial, strExpire);
        }

        public static bool RegisteSolfware(string strSerial, string expireTime)
        {
            if (!string.IsNullOrEmpty(strSerial))
            {
                bool firstTimeregist = true;
                try
                {
                    Microsoft.Win32.RegistryKey registTime = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software", true).OpenSubKey("PowerVisual").OpenSubKey("begintime");
                    string strDate = (string)registTime.GetValue("begintime");
                    var date = EncryptHelper.DecryptDES(strDate, "01250222");
                    DateTime resTime;
                    if (DateTime.TryParse(date, out resTime))
                    {
                        firstTimeregist = false;
                    }
                }
                catch
                {

                }
                try
                {
                    Microsoft.Win32.RegistryKey retkey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software", true).CreateSubKey("PowerVisual").CreateSubKey("checkid");
                    retkey.SetValue(softWareName, strSerial);

                    if (firstTimeregist)
                    {
                        Microsoft.Win32.RegistryKey registTime = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software", true).CreateSubKey("PowerVisual").CreateSubKey("begintime");
                        registTime.SetValue("begintime", EncryptHelper.EncryptDES(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "01250222"));
                    }

                    Microsoft.Win32.RegistryKey overTime = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("software", true).CreateSubKey("PowerVisual").CreateSubKey("expire");
                    overTime.SetValue("expire", expireTime);
                }
                catch
                {
                }
                if (CheckRegisteState())
                {
                    if (CheckIsExpire())
                    {
                        MessageBox.Show("注册成功!");
                    }
                    else
                    {
                        MessageBox.Show("注册成功!!!");
                    }
                }
                else
                {
                    MessageBox.Show("注册码错误!");
                }
            }
            else
            {
                MessageBox.Show("注册码错误");
            }
            return IsRegisted;
        }
        /// <summary>
        /// 给其他PC注册
        /// </summary>
        /// <param name="strSerial">(Computer.CurrentIns.CpuID + "2015").GetHashCode().ToString();</param>
        public static string GenerateSerial(string strSerial)
        {
            string msgString = "12";
            if (!string.IsNullOrEmpty(strSerial))
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] palindata = Encoding.Default.GetBytes(strSerial);//将要加密的字符串转换为字节数组
                byte[] encryptdata = md5.ComputeHash(palindata);//将字符串加密后也转换为字符数组
                msgString = Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为加密字符串
                return msgString;
            }
            else
            {
                MessageBox.Show("注册码错误");
                return "";
            }
        }
    }

    /// <summary>
    /// 计算机信息类
    /// </summary>
    public class Computer
    {
        public string AuthSerialID;
        public string CpuID;
        public string MacAddress;
        public string DiskID;
        public string IpAddress;
        public string LoginUserName;
        public string ComputerName;
        public string SystemType;
        public string TotalPhysicalMemory; //单位：M
        private static Computer _instance;

        public static Computer CurrentIns
        {
            get
            {
                if (_instance == null)
                    _instance = new Computer();
                return Computer._instance;
            }
            set { Computer._instance = value; }
        }
        internal Computer()
        {
            CpuID = GetCpuID();
            MacAddress = GetMacAddress();
            DiskID = GetDiskID();
            AuthSerialID = CpuID;
            //IpAddress = GetIPAddress();
            //LoginUserName = GetUserName();
            //SystemType = GetSystemType();
            //TotalPhysicalMemory = GetTotalPhysicalMemory();
            //ComputerName = GetComputerName();
        }
        string GetCpuID()
        {
            try
            {
                //获取CPU序列号代码
                string cpuInfo = "";//cpu序列号
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                }
                moc = null;
                mc = null;
                return cpuInfo;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
        string GetMacAddress()
        {
            try
            {
                //获取网卡硬件地址
                string mac = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        mac = mo["MacAddress"].ToString();
                        break;
                    }
                }
                moc = null;
                mc = null;
                return mac;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
        string GetIPAddress()
        {
            try
            {
                //获取IP地址
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        //st=mo["IpAddress"].ToString();
                        System.Array ar;
                        ar = (System.Array)(mo.Properties["IpAddress"].Value);
                        st = ar.GetValue(0).ToString();
                        break;
                    }
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
        string GetDiskID()
        {
            try
            {
                //获取硬盘ID
                String HDid = "";
                ManagementClass mc = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    HDid = (string)mo.Properties["Model"].Value;
                }
                moc = null;
                mc = null;
                return HDid;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
        /// <summary>
        /// 操作系统的登录用户名
        /// </summary>
        /// <returns></returns>
        string GetUserName()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    st = mo["UserName"].ToString();
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }

        /// <summary>
        /// PC类型
        /// </summary>
        /// <returns></returns>
        string GetSystemType()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    st = mo["SystemType"].ToString();
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
        /// <summary>
        /// 物理内存
        /// </summary>
        /// <returns></returns>
        string GetTotalPhysicalMemory()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    st = mo["TotalPhysicalMemory"].ToString();
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
        /// <summary>
        ///  获取计算机名称
        /// </summary>
        /// <returns></returns>
        string GetComputerName()
        {
            try
            {
                return System.Environment.GetEnvironmentVariable("ComputerName");
            }
            catch
            {
                return "unknow";
            }
            finally
            {
            }
        }
    }
}
